package com.sgu6.netty.handler;


import android.util.Log;

import com.google.gson.Gson;
import com.sgu6.middleware.enums.MachineStatusEnum;
import com.sgu6.middleware.event.DataRefreshEvent;
import com.sgu6.middleware.event.MachineCmdEvent;
import com.sgu6.middleware.event.MachineEvent;
import com.sgu6.middleware.event.MachineIdEvent;
import com.sgu6.middleware.event.MakeRiceEvent;
import com.sgu6.middleware.event.MakeWaterEvent;
import com.sgu6.middleware.event.UpdateDomainEvent;
import com.sgu6.middleware.event.UpgradeNoticeEvent;
import com.sgu6.netty.common.Constant;
import com.sgu6.netty.dto.AppAdDto;
import com.sgu6.netty.dto.AppVersionDto;
import com.sgu6.netty.dto.RemoteControlDto;
import com.sgu6.netty.dto.UpgradeNoticeDto;
import com.sgu6.netty.protobuffer.NettyMessageProto;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


public class CommandHandler extends ChannelHandlerAdapter {

    protected final String TAG = CommandHandler.class.getSimpleName();

    public CommandHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.i(TAG, "channelActive: ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessageProto.NettyMessage packet = (NettyMessageProto.NettyMessage) msg;
        if (packet.getHeader() != null && packet.getHeader().getType() == NettyMessageProto.Header.Type.COMMAND_REQ) {
            NettyMessageProto.MachineCmd returnMsg = packet.getBody().unpack(NettyMessageProto.MachineCmd.class);
            if (returnMsg != null && returnMsg.getCmd() != null) {
                NettyMessageProto.MachineCmd.Cmd cmd = returnMsg.getCmd();
                if (cmd == NettyMessageProto.MachineCmd.Cmd.UPDATE_APP) {
                    Gson gson = new Gson();
                    AppVersionDto dto = gson.fromJson(returnMsg.getOrderNoOrUrl(), AppVersionDto.class);
                    EventBus.getDefault().post(dto);
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.UPDATE_AD) {
                    Gson gson = new Gson();
                    AppAdDto dto = gson.fromJson(returnMsg.getOrderNoOrUrl(), AppAdDto.class);
                    EventBus.getDefault().post(dto);
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.MAKE_RICE) {
//                    MachineInfoCacheDto dto = new MachineInfoCacheDto();
//                    dto.setStatus(MachineStatusEnum.待机.code());
//                    MachineCache.saveMachineInfo(dto);
//                    Log.i(TAG, "CommandHandler channelRead: 接收到指令 [machineNo:" + returnMsg.getMachineNo() + " cmd:" + returnMsg.getCmd() + "]");
//                    if (packet.getHeader().getPriority() >= CommandPriorityEnum.系统级.code()) {
//                        commandApi.execStraight(returnMsg);
//                    } else {
////                        if (MachineContainer.getMachineStatus() == MachineStatusEnum.打米中.code()) {
////                            //若机器正在打米，则将命令加入命令队列
////                            MachineCache.saveMachineCommand(MachineContainer.MACHINE_NO, packet);
////                        } else if (MachineContainer.getMachineStatus() == MachineStatusEnum.待机.code()) {
////                            //若机器处于待机状态，则直接执行命令
////                            commandApi.execStraight(returnMsg);
////                        }
//                    }
                    if (returnMsg.getRiceTypeOrDest().equals(Constant.WATER)){
                        EventBus.getDefault().post(new MakeWaterEvent(returnMsg.getMakeNum(), returnMsg.getRiceTypeOrDest(), returnMsg.getOrderNoOrUrl()));
                    }else{
                        EventBus.getDefault().post(new MakeRiceEvent(returnMsg.getMakeNum(), returnMsg.getRiceTypeOrDest(), returnMsg.getOrderNoOrUrl()));
                    }
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.REFRESH) {
                    EventBus.getDefault().post(new DataRefreshEvent());
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.START) {
//                    MachineContainer.setMachineStatus(MachineStatusEnum.待机.code());
                    EventBus.getDefault().post(new MachineEvent(true));
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.STOP) {
//                    MachineContainer.setMachineStatus(MachineStatusEnum.停机.code());
                    EventBus.getDefault().post(new MachineEvent(false));
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.REMOTE_CONTROL) {
                    Gson gson = new Gson();
                    RemoteControlDto dto = gson.fromJson(returnMsg.getCommand(), RemoteControlDto.class);
                    if (dto.getType() == 1) {
                        EventBus.getDefault().post(new MachineIdEvent(true, dto.getValue()));
                    } else {
                        EventBus.getDefault().post(new MachineCmdEvent(dto.getValue()));
                    }
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.UPGRADE_NOTICE) {
//                    MachineContainer.setMachineStatus(MachineStatusEnum.停机.code());
                    Log.i(TAG, "channelRead: -------------------------------");
                    UpgradeNoticeDto dto = new Gson().fromJson(returnMsg.getCommand(), UpgradeNoticeDto.class);
                    EventBus.getDefault().post(new UpgradeNoticeEvent(dto.upgrade, dto.upgradeTime));
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.SHUTDOWN) {
                    try {
                        Log.v(TAG, "root Runtime->shutdown");
                        //Process proc =Runtime.getRuntime().exec(new String[]{"su","-c","shutdown"});  //关机
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                        proc.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.RESTART) {
                    try {
                        Log.v(TAG, "root Runtime->reboot");
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot "});  //关机
                        proc.waitFor();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else if (cmd == NettyMessageProto.MachineCmd.Cmd.UPDATE_DOMAIN) {
                    Log.i(TAG, "channelRead: ");
                    Gson gson = new Gson();
                    String value = returnMsg.getCommand();
                    UpdateDomainEvent dto = gson.fromJson(value, UpdateDomainEvent.class);
                    EventBus.getDefault().post(dto);
                }
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }


}
